<template>
  <div class="page-prod-list">
    <div class="search-bar">
      <el-form
        ref="searchFormRef"
        :inline="true"
        class="search-form"
        :model="searchForm"
        label-width="auto"
        @submit.prevent
      >
        <div class="input-row">
          <el-form-item
            prop="shopName"
            :label="$t('prodList.shopName') + ':'"
            class="search-form-item"
          >
            <el-input
              v-model="searchForm.shopName"
              type="text"
              clearable
              :placeholder="$t('prodList.shopName')"
            />
          </el-form-item>

          <el-form-item
            prop="keyword"
            :label="$t('product.prodName') + ':'"
            class="search-form-item"
          >
            <el-input
              v-model="searchForm.keyword"
              type="text"
              clearable
              :placeholder="$t('product.prodName')"
            />
          </el-form-item>

          <el-form-item
            prop="category"
            :label="$t('product.category')"
          >
            <el-tree-select
              v-model="searchForm.categoryId"
              :data="categoryList"
              :props="{
                value: 'categoryId',
                label: 'categoryName'
              }"
              check-strictly
            />
          </el-form-item>

          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="searchChange(true)"
            >
              {{ $t('product.search') }}
            </div>
            <div
              class="default-btn"
              @click="resetSearchForm()"
            >
              {{ $t('product.reset') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <div class="main-container">
      <div
        ref="closepopoverRef"
        class="table-con prod-table"
      >
        <el-table
          ref="prodListTable"
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row"
          style="width: 100%"
          @selection-change="selectionChange"
          @sort-change="changeTableSort"
          @cell-mouse-enter="enterTableRow"
          @cell-mouse-leave="leaveTableRow"
        >
          <el-table-column
            type="selection"
            prop="prodId"
            width="55"
          />

          <el-table-column
            fixed
            prop="shopName"
            :label="$t('prodList.shopName')"
            width="165"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.shopName }}</span>
            </template>
          </el-table-column>

          <el-table-column
            fixed
            prop="prodName"
            :label="$t('group.prodInfo')"
          >
            <template #default="scope">
              <div class="table-cell-con">
                <div class="table-cell-image">
                  <ImgShow :src="scope.row.pic" />
                </div>
                <span class="table-cell-text">{{ scope.row.prodName }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            prop="categoryName"
            label="分类"
            width="150"
          />

          <el-table-column
            prop="floorPrice"
            label="最低销售价"
            width="100"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ moneyFormat(scope.row.floorPrice || '0') }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="shopName"
            label="最快发货"
            width="100"
          >
            <template #default="scope">
              {{ scope.row.tradeTerm === 0 ? '当日发货' : scope.row.tradeTerm ? `${scope.row.tradeTerm}日发货` : '' }}
            </template>
          </el-table-column>

          <el-table-column
            fixed="right"
            align="center"
            :label="$t('publics.operating')"
            width="280"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  v-if="isAuth('prod:prod:update')"
                  class="default-btn text-btn"
                  @click="showProdInfo(scope.row.prodId)"
                >
                  {{ $t("prodList.lookOver") }}
                </div>

                <div
                  v-if="scope.row.selfProduct == 1 && isAuth('prod:prod:update')"
                  class="default-btn text-btn"
                  @click="onPrice(scope.row.prodId)"
                >
                  交易信息
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        v-if="dataList.length"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 商品详情弹窗 -->
    <el-dialog
      v-model="showProdInfoDialog"
      :title="$t('prodList.detailsTitle')"
      width="70%"
      class="prod-detail-dialog"
    >
      <div class="prod-row">
        <span class="row-title">{{ $t("product.platformClassification") + ':' }}</span>
        <span class="row-txt">
          <span
            v-for="(itemCategory, indexCategory) in prodInfoCategory"
            :key="indexCategory"
          >{{ itemCategory + (indexCategory < (prodInfoCategory.length - 1) ? ' > ' : '') }}</span>
        </span>
      </div>
      <div class="prod-row">
        <span class="row-title">{{ $t("product.prodName") + ':' }}</span>
        <span class="row-txt">{{ prodInfo.prodName }}</span>
      </div>
      <div class="prod-row">
        <span class="row-title">{{ $t("prodList.sellingPoints") + ':' }}</span>
        <span class="row-txt">{{ prodInfo.brief===''?'-':prodInfo.brief }}</span>
      </div>
      <div class="prod-row">
        <span class="row-title inline-block">{{ $t("product.pic") + ':' }}</span>
        <div class="flex-box-img">
          <span
            v-for="(item,index) in prodInfo.imgs"
            :key="index"
            class="detail-prod"
          >
            <ImgShow
              :src="item"
              :class-list="['prod-img']"
            />
          </span>
        </div>
      </div>
      <div
        v-if="prodInfo.prodParameterList && prodInfo.prodParameterList.length > 0"
        class="prod-row"
      >
        <span class="row-title">{{ $t('prodList.parameters') }}:</span>
        <span class="row-txt params-box">
          <span
            v-for="(item,index) in prodInfo.prodParameterList"
            :key="index"
            class="prod-params"
          >
            <span>{{ item.parameterKey }}:</span>
            <span>{{ item.parameterValue }}</span>
          </span>
        </span>
      </div>
      <div class="main-container">
        <div class="table-con table-box">
          <span class="row-title">{{ $t("prodList.specs") + ':' }}</span>
          <!-- 规格表格 -->
          <el-table
            :data="prodInfo.skuList"
            header-cell-class-name="table-header"
            row-class-name="table-row"
            class="table"
            style="width: 100%"
          >
            <el-table-column
              fixed
              prop="prodName"
              width="240"
              :label="$t('product.prodName')"
            >
              <template #default="scope">
                <span class="table-cell-text">{{ scope.row.prodName }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="partyCode"
              width="150"
              label="商品型号"
              show-overflow-tooltip
            />
            <el-table-column
              prop="properties"
              :label="$t('prodList.attribute')"
              width="240"
            >
              <template #default="scope">
                <p
                  v-if="scope.row.properties"
                  class="table-cell-text"
                >
                  {{ scope.row.properties }}
                </p>
                <p
                  v-else
                  class="table-cell-text"
                >
                  {{ $t("prodList.noAttribute") }}
                </p>
              </template>
            </el-table-column>
            <el-table-column
              prop="pic"
              :label="$t('product.pic')"
            >
              <template #default="scope">
                <img
                  v-if="scope.row.pic"
                  :key="scope.row.skuId"
                  :src="checkFileUrl(scope.row.pic)"
                  class="tab-img"
                >
                <img
                  v-else
                  :src="checkFileUrl(prodInfo.imgs[0])"
                  class="tab-img"
                >
              </template>
            </el-table-column>

            <el-table-column
              prop="price"
              :label="$t('prodList.salesPrice')"
            >
              <template #default="scope">
                {{ moneyFormat(scope.row.price || '0') }}
              </template>
            </el-table-column>
            <el-table-column
              prop="oriPrice"
              :label="$t('prodList.marketValue')"
            >
              <template #default="scope">
                {{ moneyFormat(scope.row.oriPrice || '0') }}
              </template>
            </el-table-column>
            <el-table-column
              prop="stocks"
              :label="$t('product.totalStocks')"
            />
            <el-table-column
              v-if="prodInfo.mold===0"
              prop="weight"
              :label="$t('prodList.prodWeight')"
            />
            <el-table-column
              v-if="prodInfo.mold===0"
              prop="volume"
              :label="$t('prodList.prodVolume')"
            />
          </el-table>
        </div>
      </div>
      <template #footer>
        <span
          class="dialog-footer"
        >
          <div
            class="default-btn primary-btn"
            @click="showProdInfoDialog = false"
          >{{
            $t("remindPop.confirm")
          }}</div>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, reactive } from 'vue'
import { ElMessageBox, ElMessage, ElLoading } from 'element-plus'
import { isAuth } from '@/utils'

const Data = reactive({
  tempSearchForm: null, // 保存上次点击查询的请求条件
  theParams: null, // 保存上次点击查询的请求条件
  dataForm: {
    prodName: ''
  },
  dataList: [],
  page: {
    total: 0, // 总页数
    currentPage: 1, // 当前页数
    pageSize: 10 // 每页显示多少条
  },
  searchForm: {
    shopName: '',
    keyword: '',
    status: '',
    deliveryMode: '',
    categoryId: ''
  },
  dataListSelections: [],
  currentMoveProdId: '', // 移入项的spuId
  currentClickProdId: '', // 点击项的spuId
  currentShowPopover: '', // 当前展示的弹窗
  waterSoldNum: null,
  dataListLoading: false,
  showProdInfoDialog: false,
  ProdOfflineAuditVisible: false,
  prodAuditVisible: false,
  prodName: '',
  prodNameRouter: '',
  prodId: null,
  // 0无 1.排序号排序
  sortParam: 0,
  selfProduct: null,
  // 0无 1 正序 2倒序
  sortType: 0,
  prodInfo: {},
  skuList: [],
  waterArr: [],
  categoryId: null,
  // 分类list
  categoryList: [],
  prodInfoCategory: [], // 商品详情分类
  prodListExport: [],
  // 违规下架相关
  offlineProdDialog: false, // 弹窗显隐
  offlineReason: '', // 下架原因
  offlineProdInfo: {}, // 所选下架商品的信息
  isReasonEmpty: false // 原因字段为空的提示显隐
})

const { dataList, page, searchForm, showProdInfoDialog, prodInfo, categoryList, prodInfoCategory } = toRefs(Data)

const route = useRoute()
onMounted(() => {
  if (route.query.prodName) {
    Data.prodNameRouter = route.query.prodName
    Data.prodName = route.query.prodName
  }
  Data.prodId = route.query.prodId ? route.query.prodId : null
  const parPage = useRoute().query.page
  const search = useRoute().query.search
  if (search) {
    Object.assign(Data.searchForm, JSON.parse(decodeURI(search)))
  }
  if (parPage) {
    const { total, currentPage, pageSize } = JSON.parse(decodeURI(parPage))
    Data.page.total = total
    Data.page.currentPage = currentPage
    Data.page.pageSize = pageSize
  }

  getDataList(Data.page)
  // 获取平台分类
  getCategoryList()
})

// 获取数据列表
const getDataList = (page, sort, newData = false) => {
  Data.dataListLoading = true
  if (newData || !Data.tempSearchForm) {
    Data.theParams = JSON.parse(JSON.stringify(Data.searchForm))
    Data.tempSearchForm = {
      current: page == null ? Data.page.currentPage : page.currentPage,
      size: page == null ? Data.page.pageSize : page.pageSize,
      keyword: Data.prodNameRouter ? Data.prodNameRouter : Data.prodName,
      prodId: Data.prodId ? Data.prodId : null,
      categoryId: Data.categoryId,
      selfProduct: 1,
      status: 1,
      mustNotProdTypes: !Data.searchForm.prodType ? [3] : null
    }
  } else {
    Data.tempSearchForm.current = page == null ? Data.page.currentPage : page.currentPage
    Data.tempSearchForm.size = page == null ? Data.page.pageSize : page.pageSize
  }
  if (sort) {
    Data.theParams.sort = sort === 'ascending' ? 13 : 12
  } else {
    Data.theParams.sort = null
  }
  http({
    url: http.adornUrl('/platform/search/prod/page'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        Data.tempSearchForm,
        Data.theParams
      )
    )
  }).then(({ data }) => {
    Data.dataList = data.records
    for (const key in Data.dataList) {
      // eslint-disable-next-line no-prototype-builtins
      if (Data.dataList.hasOwnProperty(key)) {
        const element = Data.dataList[key]
        element.imgs = element.pic
      }
    }
    Data.prodName = ''
    Data.prodNameRouter = null
    Data.page.total = data.total
    Data.dataListLoading = false

    // 末尾页数据为空重新请求
    if (!Data.dataList.length && Data.page.currentPage > 1) {
      Data.page.currentPage = 1
      getDataList()
    }
  })
}

const changeTableSort = (column) => {
  getDataList(Data.page, column.order)
}

// 获取平台分类列表
const getCategoryList = () => {
  Data.dataListLoading = true
  http({
    url: http.adornUrl('/prod/category/listCategoryByGrade'),
    method: 'get',
    params: http.adornParams({
      grade: 2
    })
  }).then(({ data }) => {
    Data.categoryList = treeDataTranslate(data, 'categoryId', 'parentId')
    Data.dataListLoading = false
  })
}

// 获取商品详情
const showProdInfo = (id) => {
  Data.showProdInfoDialog = true
  http({
    url: http.adornUrl(`/prod/prod/info/${id}`),
    method: 'GET'
  }).then(res => {
    res.data.imgs = res.data.imgs ? res.data.imgs.split(',') : []
    Data.prodInfo = res.data
    Data.skuList = res.data.skuList
    showProdCategory(res.data.categoryId)
  })
}

const showProdCategory = (id) => {
  http({
    url: http.adornUrl('/prod/category/getCategoryAndParent'),
    params: {
      categoryId: id
    },
    method: 'GET'
  }).then(res => {
    Data.prodInfoCategory = []
    res.data.forEach(item => {
      Data.prodInfoCategory.push(item.categoryName)
    })
  })
}

// 条件查询
const searchChange = (newData = false) => {
  Data.page.currentPage = 1
  getDataList(Data.page, false, newData)
}

const closepopoverRef = ref()

// 移入表格行
const enterTableRow = (row) => {
  Data.currentMoveProdId = row.prodId
}

// 移出表格行
const leaveTableRow = () => {
  Data.currentMoveProdId = ''
}

// 多选变化
const selectionChange = (val) => {
  Data.dataListSelections = val
}

const router = useRouter()
/**
 * 重置表单
 */
const resetSearchForm = () => {
  Data.searchForm = {
    shopName: '',
    keyword: '',
    status: '',
    deliveryMode: '',
    categoryId: ''
  }
  Data.prodId = null
  Data.selfProduct = null
}

const handleSizeChange = (val) => {
  Data.page.pageSize = val
  getDataList()
}

const handleCurrentChange = (val) => {
  Data.page.currentPage = val
  getDataList()
}

const onPrice = (id) => {
  http({
    url: http.adornUrl(`/prod/prod/info/${id}`),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    if (data.modelType == 1) {
      ElMessage.warning('选型模式暂不支持')
      // router.push({
      //   path: '/prod/manage/sprice',
      //   query: { prodId: id, page: encodeURI(JSON.stringify(page)), search: encodeURI(JSON.stringify(searchForm)) }
      // })
    } else if (data.modelType === 0 || data.modelType === 3) {
      router.push({
        path: '/self/price-manage/price',
        query: { prodId: id, shopId: data.shopId, page: encodeURI(JSON.stringify(Data.page)), search: encodeURI(JSON.stringify(Data.searchForm)) }
      })
    } else {
      ElMessage.warning('该商品尚未配置规格')
    }
  })
}

</script>

<style scoped lang="scss">
@use "index";
</style>
